<script lang="tsx" setup>
import { reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { Button, Tag } from 'ant-design-vue';
import { parseTime } from '@/utils';
import { getRoyiRoleUser, royiAuthUserCancel, royiAuthUserCancelAll, royiAuthUserSelectAll } from '@/service/api';
import Modal from '@/components/common/modal.vue';
import { useRouterPush } from '@/hooks/common/router';
import { useTabStore } from '@/store/modules/tab';
import { useRouteStore } from '@/store/modules/route';
import Search from './modules/search.vue';
import AddUser from './modules/add-user.vue';

const tabStore = useTabStore();
const { routerPushByKey } = useRouterPush();
const routeStore = useRouteStore();

const route = useRoute();
interface Props {
  id: string;
}

const props = defineProps<Props>();

const searchParams = ref({
  userName: null,
  phonenumber: null,
  // nickName: null,
  roleId: props.id
});

const columnChecks = ref([
  {
    key: 'userName',
    dataIndex: 'userName',
    title: '用户名称',
    // width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'nickName',
    dataIndex: 'nickName',
    title: '用户昵称',
    // width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'email',
    dataIndex: 'email',
    title: '邮箱',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'phonenumber',
    dataIndex: 'phonenumber',
    title: '手机号码',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'status',
    dataIndex: 'status',
    title: '状态',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.status === null) {
        return null;
      }

      const tagMap: any = {
        0: 'success',
        1: 'error'
      };

      const label = record.status == 0 ? '正常' : '异常';

      return <Tag color={tagMap[record.status] || 'error'}>{label}</Tag>;
    }
  },
  {
    key: 'createTime',
    dataIndex: 'createTime',
    title: '创建时间',
    align: 'center',
    width: 180,
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.createTime == null) {
        return null;
      }

      return parseTime(record.createTime);
    }
  },
  {
    key: 'cz',
    dataIndex: 'cz',
    title: '操作',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return (
        <Button size="small" class="m-r8px" type="link" onClick={() => handleCancelAuthorization(record)}>
          <icon-ic-round-error class="align-sub text-icon" />
          取消授权
        </Button>
      );
    }
  }
]);
const loading = ref(false);
const selectedRowKeys = ref<any[]>([]);
const tableData = ref([]);

const pagination = reactive({
  current: 1,
  pageSize: 200,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500'],
  showQuickJumper: true,
  showTotal: (total: number) => {
    return `共${total}条`;
  },
  total: 0,
  onChange: async (current: number, size: number) => {
    pagination.current = current;
    pagination.pageSize = size;
    getData();
  }
});
function tableSelectChange(val: any[]) {
  selectedRowKeys.value = val;
}

function getData() {
  const params = {
    ...searchParams.value,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  };
  getRoyiRoleUser(params).then( res => {
    const data = res.otherData
    if (data.code == 200) {
      pagination.total = data?.total || 0;
      tableData.value = data.rows;
    }
  });
  // getRoyiRoleUser(params).then(({ data, error }) => {
  //   if (!error) {
  //     pagination.total = data?.total || 0;
  //     tableData.value = data.rows;
  //   }
  // });
}

getData();

function reset() {
  search();
}

function search() {
  pagination.current = 1;
  getData();
}

// 取消授权
function handleCancelAuthorization(row?: any) {
  let userName = '';
  let title = '';
  let pro: any;
  if (row) {
    userName = row.userName;
    title = `确认要取消该用户"${userName}"角色吗？`;
    pro = royiAuthUserCancel({ userId: row.userId, roleId: props.id });
  } else {
    title = '是否取消选中用户授权数据项？';
    const userIds = selectedRowKeys.value.join();
    pro = royiAuthUserCancelAll({ userIds, roleId: props.id });
  }
  window.$modal?.confirm({
    title,
    onOk: () => {
      pro.then(({ error }) => {
        if (!error) {
          window.$message?.success('操作成功!');
          search();
          if (!row) {
            selectedRowKeys.value = [];
          }
        }
      });
    },
    onCancel: () => {}
  });
}

const visible = ref(false);
function handleAddUser() {
  visible.value = true;
}
function handleRoleOk() {
  const params = {
    roleId: props.id,
    userIds: selectList.value.join()
  };
  royiAuthUserSelectAll(params).then(({ data, error }) => {
    if (!error) {
      window.$message?.success('操作成功!');
      search();
      handleClose();
    }
  });
}

function handleClose() {
  visible.value = false;
}

const selectList = ref([]);
function addTableSelectChange(val: any) {
  selectList.value = val;
}

async function closePage() {
  const path = route.fullPath;
  const tab: any = tabStore.tabs.find(item => {
    if (item.fullPath === path) {
      return item;
    }
  });
  await tabStore.removeTab(tab.id);
  await routerPushByKey('manage_role');
  await routeStore.reCacheRoutesByKey(tab.routeKey);
}
</script>

<template>
  <div class="jl-main-page one-code-ascend min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="reset" @search="search"></Search>
    <ACard
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="table-card flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #title>
        <AButton type="primary" ghost class="mini-btn mr-8px" @click="handleAddUser">
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          <span class="ml-3px">添加用户</span>
        </AButton>
        <AButton
          type="primary"
          ghost
          class="mini-btn mr-8px"
          :disabled="!selectedRowKeys.length"
          @click="handleCancelAuthorization(null)"
        >
          <template #icon>
            <icon-ic-round-error class="align-sub text-icon" />
          </template>
          <span class="ml-3px">批量取消授权</span>
        </AButton>
        <AButton type="primary" ghost class="mini-btn mr-8px" @click="closePage">
          <template #icon>
            <icon-ic-round-close class="align-sub text-icon" />
          </template>
          <span class="ml-3px">关闭</span>
        </AButton>
      </template>
      <template #extra>
        <TableColumnSetting v-model:columns="columnChecks" />
      </template>
      <ATable
        :columns="columnChecks"
        :data-source="tableData"
        bordered
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: tableSelectChange }"
        size="small"
        :loading="loading"
        row-key="userId"
        :pagination="pagination"
        :scroll="{ x: 1680, y: 'auto' }"
        class="h-full"
      />
    </ACard>
    <Modal
      v-model:visible="visible"
      title="选择用户"
      height="70vh"
      width="80vw"
      :destroy-on-close="true"
      @ok="handleRoleOk"
    >
      <AddUser :id="props.id" @table-select-change="addTableSelectChange"></AddUser>
      <template #footer>
        <div class="modal-footer">
          <AButton type="primary" @click="handleRoleOk()">确定</AButton>
          <AButton @click="handleClose">取消</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style></style>
